import axios from 'axios';
import { message } from 'ant-design-vue';
import {getToken} from '@/utils/auth.js'

// 全局模拟数据开关
export let useMock = true;

// 导入模拟数据
import { getMockData } from '@/mock';

// 真实请求实例
export const http = axios.create({
  baseURL: '',
  timeout: 100000,
  responseType: 'arraybuffer',
  transformResponse: [data => data]
});

// 请求拦截器
http.interceptors.request.use(config => {
  const token = getToken();
  if (token) {
    config.headers['Authorization'] = `${token}`;
  }
  
  if (config.data instanceof Uint8Array) {
    config.headers['Content-Type'] = 'application/x-protobuf';
  }
  
  return config;
});

// 响应拦截器
http.interceptors.response.use(
  response => {
    // 不再自动反序列化，由调用方处理
    return response;
  },
  error => {
    let errorMsg = `网络错误: ${error.message}`;
    if (error.response) {
      switch (error.response.status) {
        case 400: errorMsg = '请求参数错误'; break;
        case 401: errorMsg = '未授权，请登录'; break;
        case 403: errorMsg = '拒绝访问'; break;
        case 404: errorMsg = '请求资源不存在'; break;
        case 500: errorMsg = '服务器错误'; break;
        default: errorMsg = `请求错误: ${error.response.status}`;
      }
      
      if (error.response.data && error.config.protoType) {
        try {
          const errorData = error.config.protoType.deserializeBinary(error.response.data);
          errorMsg = errorData.getMessage() || errorMsg;
        } catch (e) {}
      }
    }
    
    message.error(errorMsg);
    return Promise.reject({
      message: errorMsg,
      code: error.response?.status,
      raw: error
    });
  }
);

// 模拟请求实例
const mockHttp = axios.create({
  baseURL: '/mock',
  timeout: 10,
  responseType: 'arraybuffer',
  transformRequest: [(data, headers) => data],
  transformResponse: [data => data]
});

// 添加拦截器
mockHttp.interceptors.request.use(http.interceptors.request.handlers[0].fulfilled);
mockHttp.interceptors.response.use(http.interceptors.response.handlers[0].fulfilled);

// 增强mock适配器
mockHttp.defaults.adapter = async (config) => {
  try {
    await new Promise(resolve => setTimeout(resolve, 200));
    // 处理protobuf请求
    if (config.data instanceof Uint8Array) {
      const path = config.url.startsWith('/') ? config.url : `/${config.url}`;
      // 传递完整的config对象，确保headers被传递
      const mockData = await getMockData(path, config);
      if (!mockData) {
        throw new Error(`未定义的模拟接口: ${path}`);
      }

      // 返回原始数据，由调用方自行反序列化
      return {
        data: mockData.data,
        status: mockData.status || 200,
        statusText: mockData.statusText || 'OK',
        headers: mockData.headers || {}
      };
    }
    
    // 处理普通请求
    const path = config.url.startsWith('/') ? config.url : `/${config.url}`;
    const mockData = await getMockData(path, config);
    
    if (!mockData) {
      throw new Error(`未定义的模拟接口: ${path}`);
    }

    return {
      data: mockData.data,
      status: mockData.status || 200,
      statusText: mockData.statusText || 'OK',
      headers: mockData.headers || {},
      config: {
        ...config,
        ...(mockData.config || {})
      }
    };
  } catch (e) {
    console.error('Mock请求失败:', e);
    throw {
      response: {
        status: 404,
        data: e.message
      }
    };
  }
};

// 导出工具函数
export const getHttp = () => useMock ? mockHttp : http;

export const toggleMockMode = (enabled) => {
  localStorage.setItem('useMock', enabled ? 'true' : 'false');
  useMock = enabled;
  return useMock;
};

export default http;
